package com.heima.common.tess4j;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "tess4j")
@Slf4j
public class Tess4jClient {
    //数据路径
    private String dataPath;
    //语言设置
    private String language;
    public String doOCR(String imageUrl) throws TesseractException {

        ITesseract instance = new Tesseract();
        instance.setDatapath(dataPath); //数据路径
        instance.setLanguage(language); // 设置识别语言为简体中文
        String result = null;
        try {
            // 从URL读取图片
            BufferedImage image = ImageIO.read(new URL(imageUrl));
            //执行ocr识别
             result = instance.doOCR(image);
            //替换回车和tal键  使结果为一行
            result = result.replaceAll("\\r|\\n","-").replaceAll(" ","");
        } catch (TesseractException e) {
            log.error("识别失败："+e.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}
